package com.ttbj.payment.component;

import java.util.Map;
import java.util.Random;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.ttbj.util.ResultUtil;
import com.ttbj.yitongpay.bean.PassiveScanQRCodeData;
import com.ttbj.yitongpay.constant.PassiveORCodeEnum;
import com.ttbj.yitongpay.service.ScanQRCodeService;

@Component
public class PaymentService {
	private Logger log = LoggerFactory.getLogger(PaymentService.class);	
	@Autowired
	ScanQRCodeService scanQRCodeService = null; 
	/**
	 * 小程序预支付获取预支付参数如package等信息
	 * @param notifyUrl 回调url
	 * @param price 钱数
	 * @param orderNum	订单号(此参数在物流费用支付为orderNum如果为同城配送费用支付为webOrderNum)
	 * @param openId	
	 * @param keyOrWebOrderNum 此参数在物流费用支付为webOrderNum如果为同城配送费用支付时为key
	 */
	public Map<String, String> prePay(String notifyUrl, Float price, String orderNum, String openId, String keyOrWD) throws Exception {
				log.info("price :" + price + "openId :" + openId + "ID :" + keyOrWD+ "orderNum : " +orderNum);
				price = price * 100f;
				if(price<1){ResultUtil.throwExcepion(ResultUtil.createFail("messages", 231, null), "支付出错原因金额小于0.01元");}
				//四舍五入
				String fee = Math.round(price)+"";
				log.info(fee);
				PassiveScanQRCodeData data = new PassiveScanQRCodeData();
				String merOrderNum = orderNum;
				String tranAmt = fee;
				data.setMerOrderNum(merOrderNum);
				data.setSysTraceNum(merOrderNum);
				data.setTranAmt(tranAmt);
				data.setChannel(PassiveORCodeEnum.WX_SP.getDesc());
				data.setSub_openid(openId);
				 //微信小程序异步回调
				data.setBackURL(notifyUrl);
				data.setAttach(keyOrWD);
				Map<String, String> map = this.scanQRCodeService.passiveScanQrCode(data);
				return map;
			}

			public static String getNonce_str() {
				String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
				Random random = new Random();
				StringBuilder sb = new StringBuilder();
				for (int i = 0; i < 15; i++) {
					int number = random.nextInt(base.length());
					sb.append(base.charAt(number));
				}
				return sb.toString();
			}

}
